<template>
  <div>
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-tickets"></i>
        <span>优惠券列表</span>
      </div>
    <div style="margin: 10px">
      <el-input style="width:200px" suffix-icon="el-icon-search" placeholder="优惠券名称" v-model="name"></el-input>
      <el-button style="margin-left: 5px" type="primary" @click="load">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px">
      <el-button type="primary" @click="handleAdd">新增优惠券<i class="el-icon-circle-plus-outline"></i></el-button>

      <el-popconfirm
          class="ml-5"
          confirm-button-text='确定'
          cancel-button-text='我再想想'
          icon="el-icon-info"
          icon-color="red"
          title="您确定批量删除这些数据吗？"
          @confirm="delBatch"
      >
        <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
    </div>

    <template>
    <el-table :data="tableData" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="45"></el-table-column>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="优惠券名称">
              <span>{{ props.row.name }}</span>
            </el-form-item>
            <br>
            <el-form-item label="发行数量">
              <span>{{ props.row.publishCount }}</span>
            </el-form-item>
            <br>
            <el-form-item label="已领取">
              <span>{{ props.row.receiveCount }}</span>
            </el-form-item>
            <br>
            <el-form-item label="待领取">
              <span>{{ props.row.publishCount -props.row.receiveCount}}</span>
            </el-form-item>
            <br>
            <el-form-item label="已使用">
              <span>{{ props.row.useCount }}</span>
            </el-form-item>
            <br>
            <el-form-item label="未使用">
              <span>{{ props.row.publishCount -props.row.useCount}}</span>
            </el-form-item>
            <br>
            <el-form-item label="备注">
              <span>{{ props.row.note}}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="编号" width="60" align="center">
      </el-table-column>
      <el-table-column prop="name" label="优惠券名称" width="125" align="center">
      </el-table-column>
      <el-table-column prop="type" label="优惠券类型" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.type==0">
            <div class="status-icon icon1"></div>全场赠券
          </span>
          <span v-if="scope.row.type==1">
            <div class="status-icon icon1"></div>会员赠券
          </span>
          <span v-if="scope.row.type==2">
            <div class="status-icon icon1"></div>购物赠券
          </span>
          <span v-if="scope.row.type==3">
            <div class="status-icon icon1"></div>注册赠券
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="useType" label="可使用商品" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.useType==0">
            <div class="status-icon icon1"></div>全场通用
          </span>
          <span v-if="scope.row.useType==1">
            <div class="status-icon icon1"></div>指定分类
          </span>
          <span v-if="scope.row.useType==2">
            <div class="status-icon icon1"></div>指定商品
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="minPoint" label="使用门槛" align="center">
        <template slot-scope="scope">
          满{{scope.row.minPoint}}可用
        </template>
      </el-table-column>
      <el-table-column prop="amount" label="面值" align="center">
        <template slot-scope="scope">
          {{scope.row.amount}}元
        </template>
      </el-table-column>
      <el-table-column prop="platform" label="使用平台" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.type==0">
            <div class="status-icon icon1"></div>全部平台
          </span>
          <span v-if="scope.row.type==1">
            <div class="status-icon icon1"></div>移动平台
          </span>
          <span v-if="scope.row.type==2">
            <div class="status-icon icon1"></div>PC平台
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="优惠券起用时间" align="center">
      </el-table-column>
      <el-table-column prop="endTime" label="优惠券失效时间" align="center">
      </el-table-column>
      <el-table-column prop="" label="状态">
        <template slot-scope="scope">
          <span v-if="new Date(scope.row.endTime).getTime()<new Date(new Date().toLocaleDateString()).getTime()">
            <div class="status-icon icon1"></div>已过期
         </span>
          <span v-if="new Date(scope.row.startTime).getTime()>new Date(new Date().toLocaleDateString()).getTime()">
            <div class="status-icon icon1"></div>未开始
          </span>
          <span v-if="new Date(scope.row.startTime).getTime()<new Date(new Date().toLocaleDateString()).getTime()
                     &&
                     new Date(scope.row.endTime).getTime()>new Date(new Date().toLocaleDateString()).getTime()">
            <div class="status-icon icon1"></div>进行中
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="handleDetail(scope.row.id)">查看</el-button>
          <el-button type="success" @click = "handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm
              class="ml-5"
              confirm-button-text='确定'
              cancel-button-text='我再想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="handleDel(scope.row.id)"
          >
            <el-button type="danger" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>>
      </el-table-column>
    </el-table>
    </template>

    <div style="padding: 10px 0">
      <el-pagination
          :page-sizes="[5,10,15,20]"
          :page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    </el-card>
    <el-dialog title="优惠券信息" :visible.sync="dialogFormVisible" width="40%">
      <el-form label-width="150px" size="small" :rules="rules">
        <el-form-item label="优惠券类型">
          <template>
            <el-select v-model="coupon.type" placeholder="请选择">
              <el-option
                  v-for="item in options1"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="优惠券名称">
          <el-input v-model="coupon.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="通用平台">
          <template>
            <el-select v-model="coupon.platform" placeholder="请选择">
              <el-option
                  v-for="item in options2"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="总发行量">
          <el-input v-model="coupon.publishCount" autocomplete="off" placeholder="只能输入正整数"></el-input>
        </el-form-item>
        <el-form-item label="面额">
          <el-input v-model="coupon.amount" autocomplete="off" placeholder="面值只能是数值">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="单人限领">
          <el-input v-model="coupon.perLimit" autocomplete="off" placeholder="只能输入正整数">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="使用门槛">
          <el-input v-model="coupon.minPoint" autocomplete="off" placeholder="只能输入正整数">
            <template slot="prepend">满</template>
            <template slot="append">元可用</template>
          </el-input>
        </el-form-item>
        <el-form-item label="领取日期">
          <el-date-picker
              v-model="coupon.enableTime"
              value-format="yyyy-MM-dd"
              type="date"
              :picker-options="pickerOptions0"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="优惠券起用时间">
          <el-date-picker
              v-model="coupon.startTime"
              value-format="yyyy-MM-dd"
              type="date"
              :picker-options="pickerOptions1"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="优惠券失效时间">
          <el-date-picker
              v-model="coupon.endTime"
              value-format="yyyy-MM-dd"
              type="date"
              :picker-options="pickerOptions2"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="可使用商品：">
          <el-radio-group v-model="coupon.useType">
            <el-radio-button :label="0">全场通用</el-radio-button>
            <el-radio-button :label="1">指定分类</el-radio-button>
            <el-radio-button :label="2">指定商品</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="coupon.useType===1">
          <el-cascader
              clearable
              placeholder="请选择分类名称"
              v-model="selectProductCate"
              :options="productCateOptions">
          </el-cascader>
          <el-button @click="handleAddProductCategoryRelation()">添加</el-button>
          <el-table ref="productCateRelationTable"
                    :data="coupon.productCategoryRelationList"
                    style="width: 100%;margin-top: 20px"
                    border>
            <el-table-column label="分类名称" align="center">
              <template slot-scope="scope">{{scope.row.parentCategoryName}}>{{scope.row.productCategoryName}}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           @click="handleDeleteProductCateRelation(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item v-show="coupon.useType===2">
          <el-select
              v-model="selectProduct"
              filterable
              remote
              reserve-keyword
              placeholder="商品名称/商品货号"
              :remote-method="searchProductMethod"
              :loading="selectProductLoading">
            <el-option
                v-for="item in selectProductOptions"
                :key="item.productId"
                :label="item.productName"
                :value="item.productId">
              <span style="float: left">{{ item.productName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">NO.{{ item.productSn }}</span>
            </el-option>
          </el-select>
          <el-button @click="handleAddProductRelation()">添加</el-button>
          <el-table ref="productRelationTable"
                    :data="coupon.productRelationList"
                    style="width: 100%;margin-top: 20px"
                    border>
            <el-table-column label="商品名称" align="center">
              <template slot-scope="scope">{{scope.row.productName}}</template>
            </el-table-column>
            <el-table-column label="货号" align="center"  width="120" >
              <template slot-scope="scope">NO.{{scope.row.productSn}}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           @click="handleDeleteProductRelation(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="form.note" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="优惠券历史记录" :visible.sync="dialogVisible" width="70%">

      <div style="margin: 10px">
        <el-input style="width:200px" suffix-icon="el-icon-search" placeholder="优惠券码" v-model="couponCode"></el-input>
        <el-button style="margin-left: 5px" type="primary" @click="searchHistory">搜索</el-button>
        <el-button type="warning" @click="reset1">重置</el-button>
      </div>

      <el-table :data="tableData1" border>
        <el-table-column prop="couponCode" label="优惠券码" width="60" align="center">
        </el-table-column>
        <el-table-column prop="memberNickname" label="会员名称" width="125" align="center">
        </el-table-column>
        <el-table-column prop="getType" label="领取方式" align="center">
          <template slot-scope="scope">
          <span v-if="scope.row.getType==0">
            <div class="status-icon icon1"></div>后台赠送
          </span>
            <span v-if="scope.row.getType==1">
            <div class="status-icon icon1"></div>主动获取
          </span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="领取时间" align="center">
        </el-table-column>
        <el-table-column prop="useStatus" label="当前状态" align="center">
          <template slot-scope="scope">
          <span v-if="scope.row.useStatus==0">
            <div class="status-icon icon1"></div>未使用
          </span>
            <span v-if="scope.row.useStatus==1">
            <div class="status-icon icon1"></div>已使用
          </span>
            <span v-if="scope.row.useStatus==2">
            <div class="status-icon icon1"></div>已过期
          </span>
          </template>
        </el-table-column>
        <el-table-column prop="useTime" label="使用时间" align="center">
        </el-table-column>
        <el-table-column prop="orderSn" label="订单编号" align="center">
        </el-table-column>
      </el-table>
      <div style="padding: 10px 0">
        <el-pagination
            :page-sizes="[5,10,15,20]"
            :page-size="pageSize1"
            @size-change="handleSizeChange1"
            @current-change="handleCurrentChange1"
            :current-page="pageNum1"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total1">
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {fetchListWithChildren} from "@/api/productCate";
import {fetchSimpleList as fetchProductList} from '@/api/product';
import {getCoupon} from "@/api/coupon";
const defaultCoupon = {
  type: 0,
  name: null,
  platform: 0,
  amount: null,
  perLimit: 1,
  minPoint: null,
  startTime: null,
  endTime: null,
  useType: 0,
  note: null,
  publishCount: null,
  productRelationList: [],
  productCategoryRelationList: []
};
export default {
  name: "Coupon",
  data(){
    return {
      coupon: Object.assign({}, defaultCoupon),
      rules: {
        name: [
          {required: true, message: '请输入优惠券名称', trigger: 'blur'},
          {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
        ],
        publishCount: [
          {type: 'number',required: true, message: '只能输入正整数', trigger: 'blur'}
        ],
        amount: [
          {type: 'number',required: true,message: '面值只能是数值',trigger: 'blur'}
        ],
        minPoint: [
          {type: 'number',required: true,message: '只能输入正整数',trigger: 'blur'}
        ]
      },
      total:0,
      pageNum:1,
      pageSize:10,
      tableData: [],
      tableData1: [],
      total1:0,
      pageNum1:1,
      pageSize1:5,
      couponId: "",
      name:"",
      couponCode:"",
      dialogFormVisible:false,
      dialogVisible:false,
      multipleSelection:[],
      form:{},
      selectProduct:null,
      selectProductLoading: false,
      selectProductOptions:[],
      selectProductCate: null,
      productCateOptions: [],
      options1: [{
        value: '0',
        label: '全场赠券'
      }, {
        value: '1',
        label: '会员赠券'
      }, {
        value: '2',
        label: '购物赠券'
      }, {
        value: '3',
        label: '注册赠券'
      }],
      options2: [{
        value: '0',
        label: '全平台'
      }, {
        value: '1',
        label: '移动平台'
      }, {
        value: '2',
        label: 'PC平台'
      }],
      value:'',
      pickerOptions0: {
        disabledDate: (time) => {
          return time.getTime() < Date.now()
        }
      },
      pickerOptions1: {
        disabledDate: (time) => {
          let beginDateVal = this.form.enableTime;
          if (beginDateVal) {
            return (
                time.getTime() <
                new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000
            );
          }
        }
      },
      pickerOptions2: {
        disabledDate: (time) => {
          let beginDateVal = this.form.startTime;
          if (beginDateVal) {
            return (
                time.getTime() <
                new Date(beginDateVal).getTime() - 1 * 24 * 60 * 60 * 1000
            );
          }
        }
      }
    }
  },
  created(){
    this.load()
    this.getProductCateList();
  },
  methods:{
    load(){
      //请求查询数据
      this.request.get("/coupons/page",{
        params:{
          pageNum:this.pageNum,
          pageSize:this.pageSize,
          name:this.name
        }
      }).then(res =>{
        console.log(res)
        this.tableData = res.records
        this.total = res.total
      })
    },
    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageNum = pageNum
      this.load()
    },
    handleSizeChange1(pageSize) {
      console.log(pageSize)
      this.pageSize1 = pageSize
      this.handleDetail(this.couponId)
    },
    handleCurrentChange1(pageNum) {
      console.log(pageNum)
      this.pageNum1 = pageNum
      this.handleDetail(this.couponId)
    },
    handleAdd(){
      this.dialogFormVisible = true
      this.form = {}
      this.coupon =[]
    },
    save(){
      this.request.post("/coupons",this.form).then(res=>{
        if(res){
          this.$message.success("保存成功")
          this.dialogFormVisible = false
          this.load()
        }else{
          this.$message.error("保存失败")
          this.dialogFormVisible = false
        }
      })
    },
    handleEdit(row){
      getCoupon(row.id).then(response=>{
        this.coupon=response.data;
      });
      this.form = row
      this.dialogFormVisible = true
      this.load()
    },
    handleDetail(id){
      this.couponId = id;
      this.request.get("/couponhistories/page",{
        params:{
          pageNum:this.pageNum1,
          pageSize:this.pageSize1,
          couponCode:this.couponCode,
          couponId:this.couponId
        }
      }).then(res =>{
        console.log(res)
        this.tableData1 = res.records
        this.total1 = res.total
      })
      this.dialogVisible=true
    },
    searchHistory(){
      this.request.get("/couponhistories/page",{
        params:{
          pageNum:this.pageNum1,
          pageSize:this.pageSize1,
          couponCode:this.couponCode,
          couponId:this.couponId
        }
      }).then(res =>{
        console.log(res)
        this.tableData1 = res.records
        this.total1 = res.total
      })
      this.dialogVisible=true
    },
    handleDel(id){
      this.request.delete("/coupons/"+id).then(res=>{
        if(res){
          this.$message.success("删除成功")
          this.load()
        }else{
          this.$message.error("删除失败")
        }
      })
    },
    handleSelectionChange(val){
      this.multipleSelection = val
    },
    delBatch(){
      let ids = this.multipleSelection.map(v => v.id)
      this.request.post("/coupons/del/batch",ids).then(res=>{
        if(res){
          this.$message.success("批量删除成功")
          this.load()
        }else{
          this.$message.error("批量删除失败")
          this.load()
        }
      })
    },
    reset() {
      this.name = ""
      this.load()
    },
    reset1() {
      this.couponCode = ""
      this.handleDetail(this.couponId)
    },
    searchProductMethod(query){
      if (query !== '') {
        this.loading = true;
        fetchProductList({keyword:query}).then(response=>{
          this.loading=false;
          let productList = response.data;
          this.selectProductOptions = [];
          for(let i=0;i<productList.length;i++){
            let item = productList[i];
            this.selectProductOptions.push({productId:item.id,productName:item.name,productSn:item.productSn});
          }
        });
      } else {
        this.selectProductOptions = [];
      }
    },
     handleAddProductRelation(){
      if(this.selectProduct===null){
        this.$message({
          message: '请先选择商品',
          type: 'warning'
        });
        return
      }
      this.coupon.productRelationList.push(this.getProductById(this.selectProduct));
      this.selectProduct=null;
    },
    handleDeleteProductRelation(index,row){
      this.coupon.productRelationList.splice(index,1);
    },
    handleAddProductCategoryRelation(){
      if(this.selectProductCate===null||this.selectProductCate.length===0){
        this.$message({
          message: '请先选择商品分类',
          type: 'warning'
        });
        return
      }
      this.coupon.productCategoryRelationList.push(this.getProductCateByIds(this.selectProductCate));
      this.selectProductCate=[];
    },
    handleDeleteProductCateRelation(index,row){
      this.coupon.productCategoryRelationList.splice(index,1);
    },
    getProductById(id){
      for(let i=0;i<this.selectProductOptions.length;i++){
        if(id===this.selectProductOptions[i].productId){
          return this.selectProductOptions[i];
        }
      }
      return null;
    },
    getProductCateList() {
      fetchListWithChildren().then(response => {
        let list = response.data;
        this.productCateOptions = [];
        for (let i = 0; i < list.length; i++) {
          let children = [];
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              children.push({label: list[i].children[j].name, value: list[i].children[j].id});
            }
          }
          this.productCateOptions.push({label: list[i].name, value: list[i].id, children: children});
        }
      });
    },
    getProductCateByIds(ids){
      let name;
      let parentName;
      for (let i = 0; i < this.productCateOptions.length; i++) {
        if (this.productCateOptions[i].value === ids[0]) {
          parentName = this.productCateOptions[i].label;
          for (let j = 0; j < this.productCateOptions[i].children.length; j++) {
            if (this.productCateOptions[i].children[j].value === ids[1]) {
              name = this.productCateOptions[i].children[j].label;
            }
          }
        }
      }
      return {productCategoryId: ids[1], productCategoryName: name, parentCategoryName: parentName};
    }
  }
}
</script>

<style scoped>

</style>